package cn.frank.config;

import cn.frank.util.CommonVariable;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author Frank
 * @date 05-24
 */
public class DataSourceConfig {
    private static final Logger LOG = LoggerFactory.getLogger(DataSourceConfig.class);

    /*
     * 这里主要加载对应数据库的mapper.xml和对应的pojo文件.
     * 因为要加载两种数据库, 所以配置只能通过java代码来动态配置.
     */
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, String dataBaseType) throws Exception {
        LOG.info("dataBaseType:" + dataBaseType);
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setDataSource(dataSource);
        if (CommonVariable.MYSQL.equalsIgnoreCase(dataBaseType)) {
            //这里加载Mysql下面的xml文件classpath:mybatis/mybatis-config.xml cn.frank.domain.mysql,cn.frank.domain.mysql
            //classpath*:mapper/mysql/*Mapper.xml,classpath*:mapper/oracle/*Mapper.xml
            factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/mysql/*Mapper.xml"));
            factoryBean.setTypeAliasesPackage("cn.frank.domain.mysql"); //这里加载Mysql下面的对应的pojo
        } else if (CommonVariable.ORACLE.equalsIgnoreCase(dataBaseType)) {
            //这里加载Oracle下面的xml
            factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/oracle/*Mapper.xml"));
            factoryBean.setTypeAliasesPackage("cn.frank.domain.oracle"); //这里加载Oracle下面对应的pojo
        }
        //这里加载共同的config
        factoryBean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        return factoryBean.getObject();
    }

}
